package com.vm.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.vm.common.MapPage;
import com.vm.common.Page;
import com.vm.common.QueryObject;
import com.vm.common.SplitPage;
import com.vm.common.SpringContext;
import com.vm.dao.BaseDAO;
import com.vm.dao.BaseDAOImpl;
import com.vm.entity.User;


/**
 * action超类
 * 
 * @author lh 2010-04-18
 * 
 */
@SuppressWarnings("serial")
public abstract class ActionSuper extends ActionSupport implements SessionAware{
	private Map<String ,Object> session;
	/** 每一个分页页面的记录数 **/
	protected int PAGE_ROW_SIZE = 10;
	/** 显示的分页数 **/
	protected int PAGE_LINK_SIZE = 5;
	/** url中存放分页数的变量名 **/
	protected String PAGE_NUMBER_VAR_NAME = "pageNumber";
	private int pageNumber;
	// 返回的URL地址
	private String backUrl;
	// 操作成功所显示的信息O
	private String showMessage;

	private String[] menuIds;
	//按钮权限
	private Map<String,Boolean> buttonGrpMap;
	
	/** 全局更新成功后result的KEY名 **/
	public final String SHOW_MESSAGE_RESULT = "show_message";
	/**
	 * 从Action对应的配置文件根据关键字获取到消息信息
	 * @param key 关键字
	 * @param arg 消息信息
	 * @return
	 */
	private String areaNo;
	public String getResourceMessage(String key, String arg) {
		String msg = super.getText(key);
		if (msg == null) return null;
		return MessageFormat.format(msg, arg);
	}

	public String getResourceMessage(String key, String[] args) {
		String msg = super.getText(key);
		if (msg == null) return null;
		return MessageFormat.format(msg, args);
	}

	public String getBackUrl() {
		return backUrl;
	}

	public void setBackUrl(String backUrl) {
		this.backUrl = backUrl;
	}

	public String getShowMessage() {
		return showMessage;
	}

	public void setShowMessage(String showMessage) {
		this.showMessage = showMessage;
	}

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public String getContextPath() {
		return ServletActionContext.getRequest().getContextPath();
	}
	
	public String getProjectPath() {
		return ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
	}

	public String getReferer() {
		return ServletActionContext.getRequest().getHeader("referer");
	}

	public String getAreaNo(BaseDAO dao) {
		User user = (User)this.getSession().get("user");
		return dao.getAreaNo(user);
	}

	public void setAreaNo(String areaNo) {
		this.areaNo = areaNo;
	}

	/**
	 * 返回分页字符串
	 * 
	 * @param url 返回时的URL
	 * @param page 要实现分页的Page对象
	 * @return
	 */
	protected String getSplitPageLink(String url, Page page) {
		url = getContextPath() + url;
		if(page==null){
			return null;
		}
		return SplitPage.split(url, PAGE_NUMBER_VAR_NAME, page.getCount(), page.getCurrent(), PAGE_LINK_SIZE);
	}

	protected String getSplitPageLink(String url, MapPage page) {
		url = getContextPath() + url;
		if(page==null){
			return null;
		}
		return SplitPage.split(url, PAGE_NUMBER_VAR_NAME, page.getCount(), page.getCurrent(), PAGE_LINK_SIZE);
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public String[] getMenuIds() {
		return menuIds;
	}

	public void setMenuIds(String[] menuIds) {
		this.menuIds = menuIds;
	}

	public Map<String, Boolean> getButtonGrpMap() {
		return buttonGrpMap;
	}

	public void setButtonGrpMap(Map<String, Boolean> buttonGrpMap) {
		this.buttonGrpMap = buttonGrpMap;
	}
	

	/**
	 * 清除Session中的QueryObject
	 */
	public void clearQueryObject(){
		 ActionContext context = ActionContext.getContext();   
		 HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
		 request.getSession().removeAttribute("queryObject");
	}
	
	public QueryObject generateArNoSQL(QueryObject queryObject,User user,BaseDAO dao){
		BaseDAO baseDao=(BaseDAO)SpringContext.generateObject("baseDAO");
		String arNoSql="";
		String areaNo=baseDao.getAreaNo(user);
		if(!user.isSuperAdmin() && !StringUtils.isEmpty(areaNo)){
			arNoSql=" and "+queryObject.getAsName()+".arNo in ("+areaNo+") ";
		}
		String sql=queryObject.getFormSql()+" where 1=1 "+queryObject.getConditionSql()+" "+arNoSql;
		queryObject.setQuerySql(sql+queryObject.getOrderSql());
		String countSql=StringUtils.substring(sql, StringUtils.indexOf(sql, "from", 0), sql.length());
		queryObject.setCountSql("select"+queryObject.getCountFilter()+" "+countSql);
		return queryObject;
	}
	/**
	 * 附加查询
	 * @return
	 */
	public String AdditionalSQL(){
		return "";
	}
	
	/**
	 * 把单个对象的属性与值按json的数据格式输出
	 * 
	 * @param obj
	 *            pojo对象
	 */
	public void outJson(Object obj) {
		outJsonString(JSONObject.fromObject(obj).toString());
	}
	/**
	 * 把多个对象的集合按照json数据格式打印
	 * 
	 * @param array
	 */
	public void outJsonArray(Object array) {
		outJsonString(JSONArray.fromObject(array).toString());
	}

	/**
	 * 输出对象数组的json数据,如[{"code":"","descn":"","id":0,"cname":"name1"},{"code":"",
	 * "descn":"","id":0,"cname":"name2"}]
	 * 
	 * @param array
	 *            对象数组
	 * @param excludesProperties
	 *            不需要转换到json数据中的属性名称构成的数组 如String[]
	 *            {"roleses","departments","department"} 2008-7-31-liuyang
	 */
	public void outJsonArray(Object array, String[] excludesProperties) {
		JsonConfig jsonConfig = new JsonConfig();
		if (excludesProperties != null)
			jsonConfig.setExcludes(excludesProperties);
		outJsonString(JSONArray.fromObject(array, jsonConfig).toString());
	}

	/**
	 * 可以设置不需转换成json数据格式的属性
	 * 
	 * @param obj
	 *            单个对象或者多个对象的集合
	 * @param excludesProperties
	 *            不需要转换到json数据中的属性名称构成的数组 如String[]
	 *            {"roleses","departments","department"} 2008-7-15-liuyang
	 */
	public void outJsonWithoutProperty(Object obj, String[] excludesProperties) {
		JsonConfig jsonConfig = new JsonConfig();
		if (excludesProperties != null)
			jsonConfig.setExcludes(excludesProperties);
		outJsonString(JSONObject.fromObject(obj, jsonConfig).toString());
	}
	public void outString(String str) {
		try {
			PrintWriter out = ServletActionContext.getResponse().getWriter();
			out.write(str);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void outJsonString(String str) {
		ServletActionContext.getResponse().setContentType(
				"text/javascript;charset=UTF-8");
		outString(str);
	}
}
